# Contributor: Amie Raine <amie@invisiblethingslab.com>
# Maintainer: Wojtek Porczyk <woju@invisiblethingslab.com>
pkgname=gramine
_real_pkgver=1.8post~UNRELEASED
pkgver=$(printf %s "$_real_pkgver" | sed \
    -e "s:post~UNRELEASED:_git$(printf %d 0x"$(git rev-parse HEAD 2>/dev/null | cut -c1-8)"):" \
    -e 's:~:_:' \
)
pkgrel=0
pkgdesc="A lightweight usermode guest OS designed to run a single Linux application"
url="https://github.com/gramineproject/gramine"
arch="x86_64"
license="LGPL-3.0-or-later"
makedepends="
    autoconf
    binutils-dev
    bison
    cmake
    coreutils
    findutils
    gawk
    gettext
    grep
    jq
    libunwind
    linux-headers
    meson
    musl-dev
    nasm
    openssl1.1-compat-dev
    protobuf-c-compiler
    protobuf-c-dev
    py3-click
    py3-elftools
    py3-jinja2
    py3-pytest
    "
depends="
    py3-click>=6.7
    py3-cryptography>=3.1
    py3-elftools
    py3-jinja2
    py3-tomli
    py3-tomli-w
    py3-voluptuous
    "
source="$pkgname-$pkgver.tar.gz"
builddir="$srcdir/$pkgname-$_real_pkgver/"
options="!check" # tests assume a glibc environment

prepare() {
    # LDFLAGS on 3.18 contain "-Wl,-z,pack-relative-relocs", which breaks
    # Gramine, because our own loader (which relocates only LibOS and PAL)
    # does not support RELR
    LDFLAGS= meson setup \
        --wrap-mode=nodownload \
        --prefix=/usr \
        --buildtype=release \
        -Ddirect=enabled \
        -Dsgx=enabled \
        -Dlibc=musl \
        . build/

    # sanity check for version number
    test "$(meson introspect build/ --projectinfo | jq -r '.version')" = "$_real_pkgver" \
        || die '$_real_pkgver does not match what is in meson.build'

    default_prepare
}

build() {
    meson compile -C build
}

package() {
    DESTDIR="$pkgdir" meson install --no-rebuild -C build

    for pc in \
        "$pkgdir"/usr/lib/pkgconfig/ra_tls_gramine.pc \
        "$pkgdir"/usr/lib/pkgconfig/secret_prov_gramine.pc \
    ; do
        sed -i -e "s:$_real_pkgver:$pkgver:" "$pc"
    done
}

snapshot() {
    meson setup -Dskeleton=enabled -Dlibc=musl build-dist/ ../..
    meson dist -C build-dist/ --no-test --include-subprojects --format=gztar
    install -D build-dist/meson-dist/"$pkgname-$_real_pkgver".tar.gz "$pkgname-$pkgver.tar.gz"
}
